<?php

// +------------------------------------------------------
// | Name： 四川大朵 购物车管理api
// +------------------------------------------------------
// | Version： V5.0
// +------------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +------------------------------------------------------
// | Time: 2021-05-10 10:12
// +------------------------------------------------------
declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\common\IndexController;
use app\common\model\Address as AddressModel;
use app\common\model\Car as CarModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\SpecPrice as SpecPriceModel;
use app\common\model\GoodsSpecValue as GoodsSpecValueModel;
use app\common\model\User as UserModel;
use app\common\services\ShippingServices;
use app\common\services\CarServices;
use think\facade\Db;

/**
 * @xk 购物车管理api
 */
class Car extends IndexController
{
    /**
     * @xk 加入购物车
     *
     * @method createCart
     *
     * @param GoodsModel     $goodsModel     [description]
     * @param CarModel       $carModel       [description]
     * @param UserModel      $userModel      [description]
     * @param SpecPriceModel $specPriceModel [description]
     * @param SpecValueModel $specValueModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T10:16:56+080
     */
    public function createCart(GoodsModel $goodsModel,
        CarModel $carModel,
        UserModel $userModel,
        SpecPriceModel $specPriceModel,
        GoodsSpecValueModel $goodsSpecValueModel)
    {
        $param = request()->param();
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $type = isset($param['type'])?$param['type']:'cart';
            $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $sku_key = isset($param['sku_key']) ? $param['sku_key'] : '';
            $sku_value = isset($param['sku_value']) ? $param['sku_value'] : '';
            $buy_num = isset($param['buy_num']) ? $param['buy_num'] : 0;
            $spec_price_id = isset($param['spec_price_id']) ? $param['spec_price_id'] : 0;
            $carModel->validate($param, 'create'); // 验证购物车加入必要属性
            $goods_info = $goodsModel
                        ->where([['goods_id', '=', $goods_id]])->field('`goods_id`,`goods_name`,`store_id`,`picurl`,`selling_price`,`market_price`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`stock`,`is_onsell`,`vip_buy_bili`,`bonus_type`')
                        ->find();
            $user_info = $userModel
                        ->where([['user_sn', '=', $user_sn]])
                        ->field('`status`,`is_bind`,`tel`,`is_buy`')
                        ->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            // if (0 == $user_info['is_bind'] && '' == $user_info['tel']) {
            //     throw new \think\Exception('请先绑定手机号！', 404);
            // }
            if (!$goods_info || 1 != $goods_info['is_onsell']) {
                throw new \think\Exception('产品已经下架，无法加入购物车', 404);
            }
            if ($buy_num <= 0) {
                throw new \think\Exception('最少要购买一个！', 404);
            }
            // 判断产品规格
            if ('' == $sku_key && 0 == $spec_price_id) {
                $goods_spce_count = $specPriceModel->where([['goods_id', '=', $goods_id]])->count();
                if ($goods_spce_count > 0) {
                    throw new \think\Exception('请选择完整的产品规格', 404);
                }
            }
            $spec_price_info = [];
            $spec_price_info = $specPriceModel
                              ->where([['goods_id', '=', $goods_id], ['sku_key', '=', $sku_key], ['spec_price_id', '=', $spec_price_id]])
                              ->field('`selling_price`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`picurl`,`stock`,`is_onsell`')
                              ->find();
            if ('' != $sku_key && !$spec_price_info) {
                throw new \think\Exception('产品规格对应错误', 404);
            }
            $cart_data = [];
            $cart_data['goods_name'] = $goods_info['goods_name'];
            $cart_data['goods_id'] = $goods_info['goods_id'];
            $cart_data['store_id'] = $goods_info['store_id'];
            $cart_data['goods_pic'] = $goods_info['picurl'];
            $cart_data['goods_price'] = $goods_info['selling_price'];
            $cart_data['selling_price'] = $goods_info['selling_price'];
            if($user_info['is_buy'] == 1){
              $cart_data['goods_price'] =  (float)$goods_info['selling_price']*(float)$goods_info['vip_buy_bili'];
            }
            $cart_data['achievement_bili'] = $goods_info['achievement_bili'];
            $cart_data['bonus_price'] = $goods_info['bonus_price'];
            $cart_data['next_bonus_price'] = $goods_info['next_bonus_price'];
            $cart_data['bonus_type'] = $goods_info['bonus_type'];
            $cart_data['is_onsell'] = $goods_info['is_onsell'];
            $cart_data['spec_price_id'] = $spec_price_id;
            $cart_data['type'] = $type;
            $cart_data['spec_key'] = $sku_key;
            $cart_data['spec_value'] = $sku_value;
            $cart_data['buy_num'] = $param['buy_num'];
            $cart_data['user_sn'] = $param['user_sn'];
            $cart_data['is_buy'] = $user_info['is_buy'];
            if ($spec_price_info) {
              if($spec_price_info['picurl'] != '/static/common/images/no_pic.png'){
                $cart_data['goods_pic'] = $spec_price_info['picurl'];
              }
                $cart_data['goods_price'] = $spec_price_info['selling_price'];
                $cart_data['selling_price'] = $spec_price_info['selling_price'];
                if($user_info['is_buy'] == 1){
                  $cart_data['goods_price'] =  (float)$spec_price_info['selling_price']*(float)$goods_info['vip_buy_bili'];
                }
                $cart_data['achievement_price'] = $spec_price_info['achievement_price'];
                $cart_data['bonus_price'] = $spec_price_info['bonus_price'];
                $cart_data['next_bonus_price'] = $spec_price_info['next_bonus_price'];
            }
            // 判断之前是否存在该用户的该产品购物车数据 如果存在 则进行数量的更新
            $cart_info = $carModel
                        ->where([['goods_id', '=', $goods_id], ['spec_key', '=', $sku_key], ['spec_price_id', '=', $spec_price_id], ['user_sn', '=', $user_sn],['type','=','cart'],['status','=',0]])
                        ->find();
            $act = 'create';
            if ($cart_info && $cart_info['car_id'] > 0 && 0 == $cart_info['status']) {
                // 进行产品购物车部分数据的更新  产品名称  快递模板  图片 重量 是否上架 是否配送 数量等
                if($type == 'cart')
                {
                  $cart_data['buy_num'] = $param['buy_num']+$cart_info['buy_num'];
                }else{
                  $cart_data['buy_num'] = $param['buy_num'];
                }
                $act = 'edit';
            }
            switch ($type) {
              case 'cart':
                switch ($act) {
                  case 'create':
                    $res = $carModel->create($cart_data); // 写入新的数据
                    $result_msg = '加入购物车成功';
                    $resultData['car_id'] = $res->car_id;
                    $resultData['type'] = 1;
                    break;
                  case 'edit':
                    $carModel->find($cart_info['car_id'])->save($cart_data);
                    $result_msg = '更新购物车成功';
                    $resultData['car_id'] = $cart_info['car_id'];
                    $resultData['type'] = 2;
                    break;
                }
                break;
              case 'order':
                  $res = $carModel->create($cart_data); // 写入新的数据
                  $result_msg = '请确认订单';
                  $resultData['car_id'] = $res->car_id;
                break;
            }

            Db::commit();
            $result_code = 200;
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 更改购物车规格信息
     *
     * @method chanageCart
     * @param  GoodsModel          $goodsModel                [description]
     * @param  CarModel            $carModel                  [description]
     * @param  UserModel           $userModel                 [description]
     * @param  SpecPriceModel      $specPriceModel            [description]
     * @param  GoodsSpecValueModel $goodsSpecValueModel       [description]
     * @return [type]              [description]
     * @Time   2021-08-28
     * @City   青岛
     * @Author xkyinzhe            <zhonghuaxinxing@sina.cn>
     */
    public function chanageCart(GoodsModel $goodsModel,
                              CarModel $carModel,
                              UserModel $userModel,
                              SpecPriceModel $specPriceModel,
                              GoodsSpecValueModel $goodsSpecValueModel)
    {
        $param = request()->param();
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $car_id = isset($param['car_id']) ? $param['car_id'] : 0;
            $buy_num = isset($param['buy_num'])?$param['buy_num']:1;
            $user_sn = isset($car_info['user_sn'])?$param['user_sn']:'';
            $car_info = $carModel->field('`goods_id`,`car_id`,`spec_key`,`spec_value`,`spec_price_id`,`is_buy`')->find($car_id);
            $goods_id = isset($car_info['goods_id']) ? $car_info['goods_id'] : 0;
            $sku_key = isset($car_info['spec_key']) ? $car_info['spec_key'] : '';
            $sku_value = isset($car_info['spec_value']) ? $car_info['spec_value'] : '';
            $spec_price_id = isset($car_info['spec_price_id']) ? $car_info['spec_price_id'] : 0;
            $goods_info = $goodsModel
                      ->where([['goods_id', '=', $goods_id]])->field('`goods_id`,`goods_name`,`store_id`,`picurl`,`selling_price`,`market_price`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`bonus_type`,`stock`,`is_onsell`,`vip_buy_bili`')
                      ->find();
            if (!$goods_info || 1 != $goods_info['is_onsell']) {
                throw new \think\Exception('产品已经下架，无法加入购物车', 404);
            }
            // 判断产品规格
            if ('' == $sku_key && 0 == $spec_price_id) {
                $goods_spce_count = $specPriceModel->where([['goods_id', '=', $goods_id]])->count();
                if ($goods_spce_count > 0) {
                    throw new \think\Exception('请选择完整的产品规格', 404);
                }
            }
            $spec_price_info = [];
            $spec_price_info = $specPriceModel
                            ->where([['goods_id', '=', $goods_id], ['sku_key', '=', $sku_key], ['spec_price_id', '=', $spec_price_id]])
                            ->field('`selling_price`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`picurl`,`stock`,`is_onsell`')
                            ->find();
            if ('' != $sku_key && !$spec_price_info) {
                throw new \think\Exception('产品规格对应错误', 404);
            }
            $cart_data = [];
            $cart_data['goods_name'] = $goods_info['goods_name'];
            $cart_data['goods_id'] = $goods_info['goods_id'];
            $cart_data['store_id'] = $goods_info['store_id'];
            $cart_data['goods_pic'] = $goods_info['picurl'];
            $cart_data['selling_price'] = $goods_info['selling_price'];
            $cart_data['goods_price'] = $goods_info['selling_price'];
            if($car_info['is_buy'] == 1){
              $cart_data['goods_price'] = (float)$goods_info['selling_price']*(float)$goods_info['vip_buy_bili'];
            }
            $cart_data['achievement_bili'] = $goods_info['achievement_bili'];
            $cart_data['is_onsell'] = $goods_info['is_onsell'];
            $cart_data['spec_price_id'] = $car_info['spec_price_id'];
            $cart_data['spec_key'] = $car_info['spec_key'];
            $cart_data['spec_value'] = $car_info['spec_value'];
            $cart_data['buy_num'] = $buy_num;
            if ($spec_price_info) {
                $cart_data['goods_pic'] = $spec_price_info['picurl'];
                $cart_data['selling_price'] = $spec_price_info['selling_price'];
                $cart_data['goods_price'] = $spec_price_info['selling_price'];
                $cart_data['achievement_bili'] = $spec_price_info['achievement_bili'];
                if($car_info['is_buy'] == 1){
                  $cart_data['goods_price'] = (float)$spec_price_info['selling_price']*(float)$goods_info['vip_buy_bili'];
                }
            }
            $cart_info = $carModel->where([['goods_id', '=', $goods_id], ['spec_key', '=', $sku_key], ['spec_price_id', '=', $spec_price_id], ['user_sn', '=', $user_sn],['type','=','cart'],['car_id','<>',$car_id]])->find();
            $act = 'edit';
            if ($cart_info && $cart_info['car_id'] > 0 && 0 == $cart_info['status']) {
                // 进行产品购物车部分数据的更新  产品名称  快递模板  图片 重量 是否上架 是否配送 数量等
                $carModel->destroy($cart_info['car_id']);
            }
            $carModel->find($car_id)->save($cart_data);
            $result_msg = '更新购物车成功';
            Db::commit();
            $result_code = 200;
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取购物车列表
     *
     * @method getCarList
     *
     * @param CarModel $carModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T13:04:27+080
     */
    public function getCarList(CarModel $carModel, UserModel $userModel,CarServices $carServices, )
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        if ('' == $user_sn) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
        if (!$user_info) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if (1 != $user_info['status']) {
            $result_code = 404;
            $result_msg = '账户已注销';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $condition = [];
        $condition[] = ['car.user_sn', '=', $user_sn];
        $condition[] = ['car.type', '=', 'cart'];
        $condition[] = ['car.status', '=', 0]; // 当前未处理的的购物车数据
        $list = $carModel
              ->alias('car')
              ->leftJoin('store s', 's.store_id=car.store_id')
              ->leftJoin('goods g', 'g.goods_id=car.goods_id and g.`is_onsell`=1')
              ->leftJoin('specPrice sp', 'car.goods_id=sp.goods_id and sp.sku_key = car.spec_key and sp.spec_price_id = car.spec_price_id')
              ->where($condition)
              ->field('car.`car_id`,car.`goods_id`,car.`goods_name`,car.`goods_pic`,car.`spec_key`,car.`spec_value`,car.`goods_price`,car.`achievement_bili`,car.`bonus_price`,car.`next_bonus_price`,car.`spec_price_id`,car.`buy_num`,s.`store_name`,s.`store_id`,car.`status`,g.`stock`,sp.`stock` as `goods_stock`,car.status as ifchoose')
              ->withAttr('goods_pic', function ($value, $data) {
                  if ($value) {
                      return getShowUrl($value);
                  }
              })
              ->withAttr('ifchoose',function($value,$data){
                return false;
              })
              ->withAttr('goods_stock', function ($value, $data) {
                  return $value>=0?$value:$stock;
              })
              ->order('car.car_id desc')
              ->select()
              ->toArray();
        // 开始执行产品分店铺行为
        $result_count = $carModel->alias('car')->where($condition)->sum('buy_num');
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        $resultData['list'] = (array)$list;
        $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
    }
    /**
     * @xk 购物车数据删除
     *
     * @method deleteCar
     *
     * @param CarModel $carModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T13:05:30+080
     */
    public function deleteCar(CarModel $carModel, UserModel $userModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $car_id_str = isset($param['car_id_str']) ? (string)$param['car_id_str'] : '';
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            if ('' == $user_sn) {
                throw new \think\Exception('您还没有登录，请先登录！', 404);
            }
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            if ($car_id_str == '') {
                throw new \think\Exception('请选择需要删除的购物车数据', 404);
            }
            $car_id_arr = explode(',', $car_id_str);
            $carModel->destroy($car_id_arr);
            Db::commit();
            $result_code = 200;
            $result_msg = '购物车数据删除成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_msg = $e->getMessage();
            $result_code = 404;
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    /**
     * @xk 立即结算
     *
     * @method makeSure
     *
     * @param CarModel $carModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T13:46:08+080
     */
    public function makeSure(CarModel $carModel,
        UserModel $userModel,
        AddressModel $addressModel,
        CarServices $carServices,
        ShippingServices $shippingServices)
    {
        $param = request()->param();
        $car_id_str = isset($param['car_id']) ? $param['car_id'] : '';
        $address_id = isset($param['address_id']) ? $param['address_id'] : 0;
        $user_sn = isset($param['user_sn'])?$param['user_sn']:'';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        if ('' == $car_id_str) {
            $result_code = 404;
            $result_msg = '请选择需要结算的数据';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        // 查询支付方式
        $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
        // 验证用户是否为有效客户 可以下单
        if (!$user_info) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if (1 != $user_info['status']) {
            $result_code = 404;
            $result_msg = '账户已注销';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        // 地址信息获取
        $address_condition = [];
        $address_condition[] = ['user_sn','=',$user_sn];
        if ($address_id > 0) {
            $address_condition[] = ['address_id', '=', $address_id];
        }
        $address_info = $addressModel
                        ->field('`address_id`,`name`,`tel`,`user_sn`,`province`,`province_code`,`city`,`city_code`,`area`,`area_code`,`address`,`is_default`,`center`')
                        ->where($address_condition)
                        ->order(['is_default' => 'desc', 'address_id' => 'desc'])
                        ->find();
        $resultData['address_info'] = $address_info; // 地址信息传入
        // 开始验证用户身份
        // 获取产品数据
        $condition = [];
        $condition[] = ['car.user_sn', '=', $user_sn];
        $condition[] = ['car.status', '=', 0]; // 当前未处理的的购物车数据
        $condition[] = ['car.car_id', 'in', $car_id_str]; // 当前未处理的的购物车数据
        $list = $carModel
                ->alias('car')
                ->leftJoin('store s', 's.store_id=car.store_id')
                ->leftJoin('goods g', 'g.goods_id=car.goods_id and g.`is_onsell`=1')
                ->leftJoin('specPrice sp', 'car.goods_id=sp.goods_id and sp.sku_key = car.spec_key and sp.spec_price_id = car.spec_price_id')
                ->where($condition)
                ->field('car.`car_id`,car.`goods_id`,car.`goods_name`,car.`goods_pic`,car.`spec_key`,car.`spec_value`,car.`goods_price`,car.`spec_price_id`,car.`buy_num`,s.`store_name`,s.`store_id`,car.`achievement_bili`,car.`bonus_type`,car.`bonus_price`,car.`next_bonus_price`,car.`is_buy`')
                ->withAttr('goods_pic', function ($value, $data) {
                    if ($value) {
                        return getShowUrl($value);
                    }
                })
                ->withAttr('goods_stock', function ($value, $data) {
                    return $value>=0?$value:$stock;
                })
                ->order('car.car_id desc')
                ->select()
                ->toArray(); // 产品数据获取完成  产品单价
        $result = $carServices->getMakeSureList($list,$address_info);
        // 开始进行金额处理
        if (!$list) {
            $result_code = 404;
            $result_msg = '请选择需要结算的产品';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $resultData['car_list'] = $result['car_list'];
        $resultData['total_price'] = $result['total_price'];
        $resultData['all_count'] = $result['all_count'];
        $resultData['all_price'] = $result['all_price'];
        $resultData['cost_price'] = $result['cost'];
        $resultData['self_address_info'] = '自提点负责人：'.config('web_config.self_name').'<br/>'.'电话：'.config('web_config.self_tel').'<br/>'.'自提地址：'.config('web_config.self_address');
        $result_code = 200;
        $result_msg = '加载成功';
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
}
